package ldh.im.fxgui.controller;

import javafx.beans.InvalidationListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import ldh.im.fxbase.util.BeanFactory;
import ldh.im.fxbase.util.ThreadPoolUtil;
import ldh.im.fxbase.cell.ObjectListCell;
import ldh.im.fxbase.dao.UserDao;
import ldh.im.fxbase.pojo.User;
import ldh.im.fxbase.util.RegionUtil;
import ldh.im.fxgui.util.UiUtil;

import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

public class UserController implements Initializable {

    @FXML private ListView<User> userList;
    @FXML private TextField searchTextField;
    @FXML private Pane contentPane;

    private RegionUtil.FxmlBean<Node, UserInfoController> userInfoFxmlBean = null;
    private UserDao userDao = BeanFactory.getInstance().getBean(UserDao.class);

    private ObservableList<User> userDatas = FXCollections.observableArrayList();
    private FilteredList<User> filteredData = new FilteredList<>(userDatas, s -> true);

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        userList.setItems(filteredData);
//        userList.setSoftTotal(100);
        userList.setCellFactory(new ObjectListCell<>(u->{
            HBox hBox = new HBox(5);
            hBox.setAlignment(Pos.CENTER_LEFT);
            ImageView imageView = new ImageView();
            imageView.setFitWidth(50);
            imageView.setFitHeight(50);
            imageView.setImage(new Image(u.getHeadImg()));

            Label label = new Label(u.getUserName());
            hBox.getChildren().addAll(imageView, label);
            return hBox;
        }));

        searchTextField.textProperty().addListener((ob, o, n)->{
            String filter = searchTextField.getText().trim();
            if(filter == null || filter.length() == 0) {
                filteredData.setPredicate(s -> true);
            } else {
                filteredData.setPredicate(s -> s.getUserName().contains(filter));
            }
        });

        userList.getSelectionModel().selectedItemProperty().addListener((InvalidationListener)l->{
            User user = userList.getSelectionModel().getSelectedItem();
            if (user == null) return;
            if (userInfoFxmlBean == null) {
                userInfoFxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/UserInfoPage.fxml"));
                userInfoFxmlBean.getController().setUser(user);
                contentPane.getChildren().clear();
                contentPane.getChildren().add(userInfoFxmlBean.getNode());
            } else {
                userInfoFxmlBean.getController().setUser(user);
                contentPane.getChildren().clear();
                contentPane.getChildren().add(userInfoFxmlBean.getNode());
            }
        });

//        userDatas.addAll(loadUsers());
        loadUsers();
    }

    private void loadUsers() {
        String imageRoot = UiUtil.getDataFileOrCreate("datas" + File.separator + "images" + File.separator + "headImgs");
        ThreadPoolUtil.submit(()->{
            try {
//            List<User> users = new ArrayList();
//            for(int i=0; i<num; i++) {
//                User user = new User();
//                user.setUserName("demo " + i);
//                user.setHeadImg(this.getClass().getResource("/imgs/head.jpg").toExternalForm());
//                users.add(user);
//            }
                List<User> users = userDao.getDefaultUsers();
                users.forEach(u->{
                    u.setHeadImg(imageRoot + u.getHeadImg());
                });
                userDatas.addAll(users);
                return users;
            } catch (Exception e) {
                throw new RuntimeException("加载用户数据失败!", e);
            }
        });
    }
}
